# -*- coding: utf-8 -*- 
import gdata.docs.service
import gdata.docs.client

class DocInfo:
  def __init__(self, doc_type, name, resource_id, parent_id, src, entry):
    self.doc_type = doc_type
    self.name = name
    self.resource_id = resource_id
    self.parent_id = parent_id
    self.src = src
    self.entry = entry
  def set_item(self, item, parent_item):
    self.item = item
    self.parent_item = parent_item
    
class UserDoc():
  def __init__(self, account, password):
    self.account = account
    self.password = password
  def Init(self):
    try:
      self.client = None
      self.client = gdata.docs.client.DocsClient()
      self.client.ClientLogin(email=self.account + '@gmail.com', password=self.password, source='everydoc client')
      self.client.ssl=False
      self.service_client = gdata.docs.service.DocsService()
      self.service_client.ClientLogin(self.account + '@gmail.com', password=self.password, source='everydoc client')
      self.service_client.ssl=False
      
    except gdata.service.BadAuthentication:
      info = wx.AboutDialogInfo()
      info.Name = "auth error"
      wx.AboutBox(info)
      return False
      
    self.doc_dict = {}
    self.doc_folder_dict = {}
    self.doc_name_list = {}

    return self.GetRootDoc()
    
  def GetRootDoc(self):
    # get the root level folders
    uri = '/feeds/default/private/full/folder:root/contents/'
    print 'uri: ', uri
    feed = self.client.GetDocList(uri=uri)

    docinfo_list = []    
    id = ''
    for entry in feed.entry:
      print 'title: ', entry.title.text
      id = entry.resource_id.text
      #self.doc_type[entry.title.text] = entry.GetDocumentType()
      docinfo = DocInfo(entry.GetDocumentType(), entry.title.text,
                      entry.resource_id.text, 0, entry.content.src, 
                      entry)
      self.doc_dict[entry.resource_id.text] = docinfo
      docinfo_list.append(entry.resource_id.text)
      name_list = []
      name_list.append(entry.resource_id.text)
      if self.doc_name_list.has_key(entry.title.text):
        self.doc_name_list[entry.title.text].extend(name_list)
      else:
        self.doc_name_list[entry.title.text] = name_list      
    self.doc_folder_dict['root'] = docinfo_list
    
    return True
    
  def set_editor(self, editor):
    self.editor = editor
    
  def GetResourceIdByItemName(self, item_name, parentItem):
    for resource_id in self.doc_name_list[item_name]:
      doc_info = self.doc_dict[resource_id]
      if doc_info.parent_item == parentItem:
        return doc_info
    return None
    
  def GetDocument(self, doc_info):
    try:
      print 'src: ', doc_info.src
      feed = self.client.GetFileContent(uri=doc_info.src + '&exportFormat=txt')
      self.editor.SetValue(feed.decode('utf8'))
      
      #self.client.Update(doc_info.src, "test update", doc_info.doc_type)
      #doc.AtomEntry = request.Service.Update(mediaUri, textStream, DocumentContentType, entryToUpdate.Title.Text) as DocumentEntry;
      
      ms = gdata.MediaSource(file_path='test.txt',
                          content_type=gdata.docs.service.SUPPORTED_FILETYPES['TXT'])
      uri = doc_info.entry.GetEditMediaLink().href
      updated_entry = self.service_client.Put(ms, uri)
      '''
      # Update metadata
      new_entry = gdata.docs.DocumentListEntry()
      created_entry = self.service_client.Post(new_entry,'/feeds/documents/private/full')
      title = 'UpdatedTestDoc'
      created_entry.title.text = title
      updated_entry = self.doclist.Put(created_entry,
                                    created_entry.GetEditLink().href)
      ms = gdata.MediaSource(file_path='test.txt',
                          content_type=gdata.docs.service.SUPPORTED_FILETYPES['DOC'])
      uri = updated_entry.GetEditMediaLink().href
      updated_entry = self.service_client.Put(ms, uri)
      '''
    except gdata.client.RequestError:
      print 'error'
    
  def GetFolder(self, doc_info):
    if self.doc_folder_dict.has_key(doc_info.name):
      return True
    
    print 'src: ', doc_info.src
    feed = self.client.GetDocList(uri=doc_info.src)
    
    docinfo_list = []
    for entry in feed.entry:
      print 'title: ', entry.title.text
      print 'id: ', entry.resource_id.text
      child_doc_info = DocInfo(entry.GetDocumentType(), entry.title.text, 
                               entry.resource_id.text, doc_info.resource_id, 
                               entry.content.src, entry)
      self.doc_dict[entry.resource_id.text] = child_doc_info
      docinfo_list.append(entry.resource_id.text)
      name_list = []
      name_list.append(entry.resource_id.text)
      if self.doc_name_list.has_key(entry.title.text):
        self.doc_name_list[entry.title.text].extend(name_list)
      else:
        self.doc_name_list[entry.title.text] = name_list 
    self.doc_folder_dict[doc_info.resource_id] = docinfo_list
    return True
  